package org.myredis.config;

import org.myredis.service.RedisService;
import org.myredis.service.RedisServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@ConditionalOnClass({JedisPoolConfig.class,JedisPool.class,RedisService.class})
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {
	@Autowired
	private RedisProperties properties;
	
	@Bean
	@ConditionalOnMissingBean(JedisPoolConfig.class)
	public JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(properties.getMaxTotal());
		jedisPoolConfig.setMaxWaitMillis(properties.getMaxWaitMillis());
		return jedisPoolConfig;
	}
	
	@Bean
	@ConditionalOnMissingBean(JedisPool.class)
	@ConditionalOnBean(JedisPoolConfig.class)
	public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig) {
		JedisPool jedisPool = new JedisPool(jedisPoolConfig,properties.getHost(),properties.getPort());
		return jedisPool;
	}
	
	@Bean
	@ConditionalOnMissingBean(RedisService.class)
	@ConditionalOnBean(JedisPool.class)
	public RedisService redisService(JedisPool jedisPool) {
		RedisServiceImpl service = new RedisServiceImpl();
		service.setJedisPool(jedisPool);
		return service;
	}

}
